package common.server.utils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Map;

public class HttpResponse {

	private int responseCode;
	private String redirectUrl;
	private Map<String, String> headers;
	private InputStream inputStream;
	private HttpURLConnection connection;

	public HttpResponse(HttpURLConnection connection, int responseCode, String redirectUrl, Map<String, String> headers, InputStream inputStream) {
		this.connection = connection;
		this.responseCode = responseCode;
		this.redirectUrl = redirectUrl;
		this.headers = headers;
		this.inputStream = inputStream;
	}

	/**
	 * 获取响应头信息,忽略大小写
	 * 
	 * @param name
	 * @return
	 */
	public String getHeader(String name) {
		if (headers == null) {
			return null;
		} else {

			if (headers.containsKey(name)) {
				return headers.get(name);
			} else if (name != null) {
				for (String key : headers.keySet()) {
					if (key != null && key.equalsIgnoreCase(name)) {
						return headers.get(key);
					}
				}
				return null;
			} else {
				return null;
			}
		}
	}

	/**
	 * 获取响应流
	 * 
	 * @return
	 */
	public InputStream getInputStream() {
		return inputStream;
	}

	/**
	 * 获取所有响应头
	 * 
	 * @return
	 */
	public Map<String, String> getHeaders() {
		return headers;
	}

	/**
	 * 获取响应码
	 * 
	 * @return
	 */
	public int getResponseCode() {
		return responseCode;
	}

	/**
	 * 获取跳转地址
	 * 
	 * @return
	 */
	public String getRedirectUrl() {
		return redirectUrl;
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (Exception e) {
			}
		}
		if (connection != null) {
			try {
				connection.disconnect();
			} catch (Exception e) {
			}
		}
	}

}
